# 用户相关逻辑
# 导入蓝图模块
from flask import Blueprint
from db import databases,make_password
# 导入flask 基础的方法
from flask import request,jsonify
import json
#导入加密类
from settings import myjwt
# 导入os  文件上传接口用
import os

# 实例化蓝图对象
user = Blueprint("user",__name__)

# 文件上传接口
@user.route('/upload/',methods=['POST','GET'])
def upload():

    # post 根据浏览器body传  无论多大 都可以上传
    #接受参数
    f = request.files['file']
    # 用来保存用户头像得信息
    id = request.form.get("id")
    # 写文件操作
            #路径    ，                文件名称
    f.save(os.path.join("./static/upload",f.filename))


    databases.update("update `user` set `img` = '%s' where id = %s" % (f.filename,id))




    return {'code':200,'msg':'上传成功','filename':f.filename}



# flask中间件使用
@user.before_request
def before_request():

    # 如果 request.path 进到 user/logininfo里面
    if request.path in ['/user/logininfo/']:
        id = request.args.get('id')
        token = request.args.get('token')

        try:
            decode_token = myjwt.decode_jwt(token)
        except Exception as e:
            return {'code': 10013, 'msg': '您的密钥不合法'}

        if str(id) != str(decode_token['id']):
            return {"code": 10012, 'msg': '您无权访问该用户信息'}
        print("经过中间件")
        print(request.path)




# 展示用户信息接口
@user.route('/logininfo/',methods=['GET'])
def logininfo():
    id = request.args.get('id')


    sql = "select * from `user` where id='%s'" % id
    res = databases.get_one(sql)
    res['code'] = 200
    return jsonify(res)



#注册
@user.route('/register/',methods=['POST','GET'])
async def register():
    data = json.loads(request.data)
    m_password = make_password(data['password'])

    sql = ("insert into `user`(`username`,`password`,`phone`) value('%s','%s','%s')" %(data['username'],m_password,data['phone']))
    print(sql)
    try:
        databases.insert(sql)
        return {'code': 200, 'msg': '注册成功'}
    except:
        return {"code":10010,'msg':'用户已经存在'}




# 导入数据库中操作类
# 导入验证码类
from settings import Code
import redis


# 获取用户信息
@user.route('/userinfo/',methods=['GET'])
async def userinfo():
    id = request.args.get('id',0)

    #查询数据库
    res = databases.get_one("select * from `user` where id =%s" % id)

    return jsonify(res)



# 发送验证码
@user.route('/sendmsg/',methods=['GET'])
async def sendmsg():

    phone = request.args.get('phone','')

    code = Code()  #b'132' 二进制字节码  不能直接用  3.3版本的redis需要手动转换  3.5版本不需要手动转换

    s = code.send_code(phone)
    print(s)
    return {"code":s,"msg":"发送成功 "}




# 登录
@user.route('/login/',methods=['GET','POST'])
async def login():
    # 转换json类型
    # data = json.loads(request.data)
    # # #接受参数
    # username = data['username']
    # password = data['password']
    # m_password = make_password(password)
    # print(username,password)

    username = request.args.get('username','')
    password = request.args.get('password')
    # print(username,password)

    phone = request.args.get('phone','')
    code = request.args.get('code')
    # print(code)

    if username:
        #查询逻辑
        sql = "select * from `user` where username = '%s' and password = '%s'" %(username,make_password(password))

        # 查询到用户
        res = databases.get_one(sql)
        # print(res)
        if res:

            #进行加密操作
            token = myjwt.encode_jwt({'id':res['id'],'username':res['username']})

            return {'code':200,'id':res['id'],'username':res['username'],'token':token}
        else:
            return {"code":403,'msg':'您的用户名或者密码错误'}
    else:
        # 获取验证码
        # 查询逻辑
        sql = "select * from `user` where phone = '%s'" % phone

        # 查询到用户
        res = databases.get_one(sql)
        # print(res)


        r= redis.Redis()
        code_redis = r.get(phone)

        #转码
        try:
            code_redis = code_redis.decode('utf-8')
        except Exception as e:
            print(e)
        # 判断第三种情况 也就是过期的情况
        if code_redis is None:  #==比对value 只   is比对地址
            return {"code":10011,'msg':'您的验证码已过期'}

        if res:
        #验证码比较
            if code ==code_redis:
                #加密
                token = myjwt.encode_jwt({'id': res['id'], 'username': res['username']})

                return {'code': 200, 'id': res['id'], 'username': res['username'], 'token': token}
            else:
                return {'code':10010,'msg':'您的验证码有误'}

    # try:
    #     res = database.get_one(sql)
    # except:
    #     pass





